package com.cskaoyan.service;

import com.cskaoyan.bean.User;
import com.cskaoyan.bean.UserExample;
import com.cskaoyan.bean.user.SearchHistory;
import com.cskaoyan.bean.user.SearchHistoryExample;
import com.cskaoyan.mapper.SearchHistoryMapper;
import com.cskaoyan.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SearchHistoryServiceImpl implements SearchHistoryService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    SearchHistoryMapper searchHistoryMapper;

    @Override
    public void insertSearchHistory(String username, String keyword) {
        UserExample example = new UserExample();
        UserExample.Criteria userCriteria = example.createCriteria();
        if (!StringUtils.isEmpty(username)) {
            userCriteria.andUsernameEqualTo(username);
        }
        List<User> userList = userMapper.selectByExample(example);
        if (userList != null && userList.size() > 0) {
            User user = userList.get(0);
            SearchHistory searchHistory = new SearchHistory();
            searchHistory.setUserId(user.getId());
            searchHistory.setKeyword(keyword);
            searchHistory.setFrom("wx");
            searchHistory.setAddTime(new Date());
            searchHistory.setUpdateTime(new Date());
            searchHistoryMapper.insertSelective(searchHistory);
        }
    }

    @Override
    public boolean deleteSearchHistory(String username) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        if(!StringUtils.isEmpty(username)){
            criteria.andUsernameEqualTo(username);
        }
        List<User> userList = userMapper.selectByExample(example);
        User user = null;
        if(userList != null && userList.size() > 0){
            user = userList.get(0);
        }

        if(user != null) {
            SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
            SearchHistoryExample.Criteria criteria1 = searchHistoryExample.createCriteria();
            criteria1.andUserIdEqualTo(user.getId());
            int delete = searchHistoryMapper.deleteByExample(searchHistoryExample);
            if(delete == 0) return false;
            return true;
        }
        return false;
    }
}
